const { developmentChains, networkConfig, LOCK_TIME, waitConfirmations } = require("../help-hardhat-config");
const { ethers } = require("hardhat");

module.exports = async function ({ getNamedAccounts, deployments, network }) {
    try {
        const { deploy } = deployments;
        const { firstAccount } = await getNamedAccounts();
        
        console.log("部署网络:", network.name);
        console.log("部署账户:", firstAccount);
        console.log("等待确认数:", waitConfirmations);

        // 获取数据源合约地址
        let dataFeedAddress;
        if (developmentChains.includes(network.name)) {
            dataFeedAddress = (await deployments.get("MockV3Aggregator")).address;
        } else {
            dataFeedAddress = networkConfig[network.config.chainId].ethUsdDataFeed;
        }
        
        console.log("使用 Price Feed 地址:", dataFeedAddress);

        // 检查账户余额
        const balance = await ethers.provider.getBalance(firstAccount);
        console.log("部署账户余额:", ethers.formatEther(balance), "ETH");

        if (balance.toString() === "0") {
            throw new Error("部署账户余额为0，请确保有足够的ETH支付gas费用");
        }

        console.log("开始部署 FundMe 合约...");
        
        const deployResult = await deploy("FundMe", {
            from: firstAccount,
            args: [LOCK_TIME, dataFeedAddress],
            log: true,
            waitConfirmations: waitConfirmations || 1,
            gasLimit: 5000000, // 添加固定的 gas limit
        });

        console.log("FundMe 部署成功！地址:", deployResult.address);

        // 验证合约
        if (network.config.chainId === 11155111 && process.env.ETHER_SCAN_API_KEY) {
            console.log("等待 Etherscan 验证...");
            try {
                await hre.run("verify:verify", {
                    address: deployResult.address,
                    constructorArguments: [LOCK_TIME, dataFeedAddress],
                });
                console.log("合约验证成功！");
            } catch (error) {
                console.log("合约验证失败:", error.message);
            }
        }

        return deployResult;
    } catch (error) {
        console.error("部署过程中发生错误:");
        console.error(error);
        throw error;
    }
}

module.exports.tags = ["all", "fundme"];